package codeRandomThoughts.Test1005K次取反后最大化的数组和;

import java.util.Arrays;
import java.util.stream.IntStream;

public class Solution2 {
    public int largestSumAfterKNegations(int[] nums, int k) {

        //先把数组按照绝对值大小排序
        nums = IntStream.of(nums)
                .boxed()
                .sorted((num1, num2) -> Math.abs(num2) - Math.abs(num1))
                .mapToInt(Integer::intValue).toArray();

        //从前往后遍历,遇到负数就k--
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            if (nums[i] < 0 && k > 0) {
                nums[i] = -nums[i];
                k--;
            }
        }

        //如果k还大于0,说明已经没有负数了
        //对数组里最小的数字进行取反操作
        if (k % 2 != 0) nums[len - 1] = -nums[len - 1];

        return Arrays.stream(nums).sum();
    }
}
